package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.SupplierProjectAcceptDTO;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.sys.SysUser;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.util.DateUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2021/4/7
 * @description 情形1、X日内无人应接：给需方发送“服务费提高”通知：您发布的XXX项目，X日内无人应接，系统建议调整服务费或招标截止时间，请确认！
 * 点击链接可以直接进入到供需详情编辑页面修改服务费和招标截止时间。
 */

@Log
public class WbXDaysNoAcceptNoticeJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("JobDemo1：启动任务=======================");
        run();
        System.out.println("JobDemo1：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        log.info("WbXDaysNoAcceptNoticeJob=======开始==================================");
        String lockkey = "WbXDaysNoAcceptNoticeJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            //(1) x天后,无人应接给你x方发送消息 “服务费提高”通知
            saveSendXfDays();

        } catch (Exception e) {
            log.info("WbXDaysNoAcceptNoticeJob=======出现异常了==================================");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            log.info("WbXDaysNoAcceptNoticeJob=======释放锁==================================");
            unlock(lockkey, uuId);
        }
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description: x天后给你x方发送消息
     * @Date:15:31 2021/4/12
     */
    public void saveSendXfDays() {
        try {
            // 外部发布的单位 设置的 x天数无响应的处理
            List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.WX.getType());
            String xvalue = "";
            if (typeListSsbl.size() > 0) {
                BaseDict bzjbl = typeListSsbl.get(0);
                xvalue = bzjbl.getBadtLevel1();
            }
            // 查询无应接记录的数据
            SupplierProjectDTO project = new SupplierProjectDTO();
            project.setStatus("006");
            project.setPublishType("002");// 002 外部发布的项目
            List<SupplierProjectDTO> list = supplierProjectManagerService.selectMyProjectListNotAccept(project);
            for (int i = 0; i < list.size(); i++) {
                SupplierProject dto = list.get(i);
                String zbEndDatestr = dto.getZbEndDate();
                Double x = Double.valueOf(xvalue) * 24;
                int i2 = x.intValue();

                Date zbEndDate = DateUtil.parseDate(zbEndDatestr, "yyyy-MM-dd HH:mm");
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(zbEndDate);
                calendar.add(Calendar.HOUR, -i2);
                /*招标截止是时间x天之前 */
                Date datebeforex = new Date(calendar.getTimeInMillis());
                Date currdate = new Date();
                if (currdate.after(datebeforex)) {
                    // 到了提醒时间 没有提醒过
                    ProjectNotice notice = new ProjectNotice();
                    notice.setLinkId(dto.getSupProjectId());
                    notice.setNoticeType("104");
                    int i1 = projectNoticeServie.selectCount(notice);
                    if (i1 == 0) {
                        sendNoticeToXf(dto, xvalue);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }

    /**
     * @param project
     * @Author:zhaoyongke
     * @Description: 发送需方
     * @Date:14:30 2021/4/7
     */
    public void sendNoticeToXf(SupplierProject project, String days) throws Exception {
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(project.getCreateBy());
        notice.setTitle("您发布的" + project.getProjectName() + "项目，" + days + "日内无人应接，系统建议调整服务费或招标截止时间，请确认");
        notice.setNoticeType("104");// 外部单位 x天 无应接 提醒
        notice.setApplicantType("002");// 供需
        notice.setContent(project.getProjectName());
        notice.setCreateDate(DateUtil.getCurrentDateString());
        projectNoticeServie.insertSelective(notice);
    }

    public void lock(String key, String uuId) {
        for (; ; ) {
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }


}
